<!-- by 7527189 2 0 -->
<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="24">
                <!-- @dropdownVisibleChange="refreshData" -->
                <a-form-item label="项目名" :labelCol="labelCol" :wrapperCol="wrapperCol" >
                  <a-tree-select  showSearch style="width:100%" :dropdownStyle="{maxHeight:'500px',overflow:'auto'}" allow-clear   :filterTreeNode="filterOption"
                   :treeData="categoryTree" v-model="activeValue"  placeholder="请选择项目" @change="selectchange" @click="refreshData" >               
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <!-- queryParam.categoryId -->
              <a-col :md="6" :sm="24">
                <a-form-item label="关键词" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入名称、工艺、材质、备注查询" v-model="queryParam.materialParam"  ref="search"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24"  style="display:none;">
                <a-form-item label="颜色" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入颜色查询" v-model="queryParam.color"></a-input>
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="6" :sm="24">
                  <!-- <a-button type="primary" @click="searchQuery">查询</a-button> -->
                  <a-button type="primary" @click="searchKeywords">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
                  <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? '收起' : '展开' }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a> -->
                </a-col>
              </span>
              <!-- <template v-if="toggleSearchStatus" >                
                <a-col :md="6" :sm="24">
                  <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input placeholder="请输入备注查询" v-model="queryParam.remark"></a-input>
                  </a-form-item>
                </a-col>
              </template> -->
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator"  v-show="showOperator" style="margin-top: 5px">       
           <a-button v-if="btnEnableList.indexOf(1)>-1" @click="handleAddDetailList(current_subtableID)" type="primary" icon="plus">新增</a-button>

          <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"  :beforeUpload="beforeUpload" @change="handleImportExcel">
            <a-popover title="表格模板">
              <template slot="content">
                <p><a target="_blank" href="/doc/goods_template.xls"><b>导入Excel模板下载</b></a></p>
              </template>
              <a-button type="primary" icon="import">导入</a-button>
            </a-popover>
          </a-upload> -->
          <a-button type="primary" icon="download" @click="handleExportXls('')">导出</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item key="1" v-if="btnEnableList.indexOf(1)>-1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>           
            </a-menu>
            <a-button>
              批量删除 <a-icon type="down" />
            </a-button>
          </a-dropdown>
          <a-popover trigger="click" placement="right">
            <template slot="content">
              <a-checkbox-group @change="onColChange" v-model="settingColumns" :defaultValue="settingColumns">
                <a-row style="width: 500px">
                  <template v-for="(item,index) in defColumns">
                    <template>
                      <a-col :span="8" :key="index">                      
                        <a-checkbox :value="item.dataIndex">
                          <j-ellipsis :value="item.title" :length="10"></j-ellipsis>
                        </a-checkbox>
                      </a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
            <a-button icon="setting">请选择要导出的列</a-button>
          </a-popover>
        </div>
      
        <a-tabs  v-model="activeKey"  @change="tabchangecallback"  >
            <a-tab-pane :tab="item.name" v-for="item in tabList" :key="item.key">            
            </a-tab-pane>
        </a-tabs>

        <!-- table区域-begin -->
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="showDataList"
            :pagination="ipagination"
            :scroll="scroll"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, columnWidth:'2%'}"
            @change="handleTableChange">
            <span slot="action" slot-scope="text, record">            
            <a @click="handleEditDetail(record)">编辑</a> 
              <!-- <a-divider v-if="btnEnableList.indexOf(1)>-1" type="vertical" />
              <a-popconfirm v-if="btnEnableList.indexOf(1)>-1" title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                <a>删除</a>
              </a-popconfirm> -->
            </span>
            <template slot="customRenderEnabled" slot-scope="enabled">
              <a-tag v-if="enabled" color="green">启用</a-tag>
              <a-tag v-if="!enabled" color="orange">禁用</a-tag>
            </template>
            <template slot="customRenderEnableSerialNumber" slot-scope="enableSerialNumber">
              <a-tag v-if="enableSerialNumber==1" color="green">有</a-tag>
              <a-tag v-if="enableSerialNumber==0" color="orange">无</a-tag>
            </template>
            <template slot="customRenderEnableBatchNumber" slot-scope="enableBatchNumber">
              <a-tag v-if="enableBatchNumber==1" color="green">有</a-tag>
              <a-tag v-if="enableBatchNumber==0" color="orange">无</a-tag>
            </template>
          </a-table>
        </div>
        <!-- table区域-end -->
        <!-- 表单区域 -->
        <material-modal ref="modalForm" @ok="modalFormOk"></material-modal>
        <MaterialAddDetailModal ref="modaladddetailForm" @detailok="addListOK"></MaterialAddDetailModal>
        <batch-set-info-modal ref="batchSetInfoModalForm" @ok="modalFormOk"></batch-set-info-modal>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
  import MaterialModal from './modules/MaterialModal'
  import MaterialAddDetailModal from './modules/MaterialAddDetailModal'
  import BatchSetInfoModal from './modules/BatchSetInfoModal'
  import { queryMaterialCategoryTreeList, getProject, getsubtable, getdetailList,getDetailListSearch } from '@/api/api' 
  import {USER_ID} from "@/store/mutation-types"

  //getProject 获取根项目 getsubtable获取每个项目的子表 getdetailList 获取子表的内容
  import { postAction } from '@/api/manage'
  import { getMpListShort } from '@/utils/util'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import JEllipsis from '@/components/jeecg/JEllipsis'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'

  var  userid = Vue.ls.get(USER_ID)
  // var current_projectID = ""
  // var current_subtableID = ""

  export default {
    name: "MaterialList",
    mixins:[JeecgListMixin],
    components: {
      MaterialModal,
      MaterialAddDetailModal,
      BatchSetInfoModal,
      JEllipsis,
      JDate
    },
    data () {
      return {
        categoryTree:[],
        mPropertyListShort: '',
        model: {},
        labelCol: {
          span: 5
        },
        wrapperCol: {
          span: 18,
          offset: 1
        },
        // 查询条件
        queryParam: {          
          categoryId:'',
          materialParam:'',
          color:'',
          weight:'',
          expiryNum:'',
          enabled: '',
          enableSerialNumber:'',
          enableBatchNumber:'',
          remark:'',
          mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        },
        ipagination:{
          pageSizeOptions: ['10', '20', '30', '100', '200']
        },
        current_category:"",
        activeName:1,
        activeKey:"",
        tableActiveName:"",
        activeValue:"",    
        showOperator:false, //新增 删除 导出按钮操作行 显示与否
        projectActiveName:"",
        current_projectID:"", //工程ID
        current_project_endtime:"", //当前工程的一些信息
        current_project_manager:"",
        current_project_num:"",
        current_project_proNo:"",
        current_subtableID:"" ,  //子表ID 
        search_keywords:"", //查询的关键字
        showDataList:[], //表格数据
        // 实际表头
        columns:[
            { title: '图号', dataIndex: 'image_num', key: 'image_num' },
            { title: '名称', dataIndex: 'name', key: 'name'}, // ,onFilter: (value, record) => record.title.indexOf(value) >= 0
            { title: '材质', dataIndex: 'makeup', key: 'makeup'},
            { title: '工艺要求', dataIndex: 'tech', key: 'tech'},
            { title: '件数', dataIndex: 'nums', key: 'nums' },
            { title: '备注', dataIndex: 'remark', key: 'remark' },
            { title: '表面处理', dataIndex: 'ext2', key: 'ext2' },
            { title: '单位', dataIndex: 'ext3', key: 'ext3' },
            { title: '仓库', dataIndex: 'ext4', key: 'ext4' },
            { title: '检验', dataIndex: 'ext5', key: 'ext5' },
            { title: '申领', dataIndex: 'ext6', key: 'ext6' },
            { title: '采购件', dataIndex: 'ext7', key: 'ext7' },
            { title: '版本', dataIndex: 'ext8', key: 'ext8' },
            { title: '品牌', dataIndex: 'ext9', key: 'ext9' },
            { title: '单台数量', dataIndex: 'ext10', key: 'ext10' },
            {
              title: '操作',
              dataIndex: 'action',
              key: 'action',
              scopedSlots: { customRender: 'action' }
            }
        ],
        // 初始化设置的表头
        settingColumns:['image_num','name','makeup','tech','nums','remark','ext2','ext3', 'ext4',
          'ext5','ext6','ext7','ext8','ext9','ext10','action'],
        // 默认的列
        defColumns: [
            { title: '图号', dataIndex: 'image_num', key: 'image_num' },
            { title: '名称', dataIndex: 'name', key: 'name'}, // ,onFilter: (value, record) => record.title.indexOf(value) >= 0
            { title: '材质', dataIndex: 'makeup', key: 'makeup'},
            { title: '工艺要求', dataIndex: 'tech', key: 'tech'},
            { title: '件数', dataIndex: 'nums', key: 'nums' },
            { title: '备注', dataIndex: 'remark', key: 'remark' },
            { title: '表面处理', dataIndex: 'ext2', key: 'ext2' },
            { title: '单位', dataIndex: 'ext3', key: 'ext3' },
            { title: '仓库', dataIndex: 'ext4', key: 'ext4' },
            { title: '检验', dataIndex: 'ext5', key: 'ext5' },
            { title: '申领', dataIndex: 'ext6', key: 'ext6' },
            { title: '采购件', dataIndex: 'ext7', key: 'ext7' },
            { title: '版本', dataIndex: 'ext8', key: 'ext8' },
            { title: '品牌', dataIndex: 'ext9', key: 'ext9' },
            { title: '单台数量', dataIndex: 'ext10', key: 'ext10' },
            {
              title: '操作',
              dataIndex: 'action',
              key: 'action',
              scopedSlots: { customRender: 'action' }
            }
        ],
        url: {
          list: "/material/list",
          delete: "/material/delete",
          deleteBatch: "/material/deleteBatch",
          importExcelUrl: "/material/importExcel",
          exportXlsUrl: "/material/exportExcel",
          batchSetStatusUrl: "/material/batchSetStatus",
          batchSetMaterialCurrentStockUrl: "/material/batchSetMaterialCurrentStock"
        },
        tabList: [        
        ],
        activeName: 'first',
        currentView: 'first'
      }
    },
    created() {
      this.model = Object.assign({}, {});
      this.initColumnsSetting()    
      this.getParentProject(); //获得类别 所有项目        
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`;
      }
    },
    methods: {
      filterOption (value, option) {      
        return option.componentOptions.propsData.title.indexOf(value) >= 0
      },
      searchKeywords(){
        let keywords = this.$refs.search.value  

        this.showDataList.length = 0
        for(let i in this.dataList)
        {
          let item = this.dataList[i]
          if(item.name.indexOf(keywords) != -1)
          {
            this.showDataList.push(item)
          }
        }
      },
      selectchange(value, label, extra){ //treeselect选择变化时触发的函数
          //value = 3 //项目id 
          //label = ['0223压缩机_818'] 项目名
          //选择的时候第一件事情 是更新一下 categoryTreeData
          this.getsubTable(value)
          this.current_projectID = value
          this.projectActiveName = label[0]
         
      },
      refreshData(){
        //console.log("getParentProject()")
        this.getParentProject()
      },
      getParentProject(){
        let that = this
        let params = {}
        params.tenant_id = userid

        let DataSource = []
        getProject(params).then((res)=>{
          //获得类别treeSelect数据      
          //that.categoryTree = res
          //原来的数据是 "prono":"su689-123","manager":"Anna","childrens":[],"num":"50","name":"0625振动盘_new2_8181","endtime":"2023.1","id":1,"serialno":"1"}
          //重新组织下 treeSelect默认字段是 {"children":[{"children":[],"checked":false,"id":23,"state":"open","title":"震动盘子表2_0818","value":23,"key":23}],"checked":false,"id":1,"state":"state","title":"0625振动盘_new2_8181","value":1,"key":1}
          res.forEach((item,index) => {
            let tmp = {}
            tmp.children = []
            tmp.checked = false
            tmp.id = item.id
            tmp.state = "state"
            tmp.title = item.name
            tmp.value = item.id
            tmp.key = item.id
            tmp.endtime = item.endtime
            tmp.num = item.num
            tmp.proNo = item.prono
            tmp.manager = item.manager
            DataSource.push(tmp)            
          });
 
          that.categoryTree = DataSource          
       
          let defalutValue =  that.categoryTree[0].id

          this.current_projectID = defalutValue

          this.getsubTable(defalutValue);  //获得项目对应的子表 默认是第一个项目
          this.activeValue = that.categoryTree[0].id
          this.projectActiveName = that.categoryTree[0].title        
        })
      },
      getsubTable(){ //获得某一项目下的子表 用来构件tab      
        let projectID = arguments[0]

        this.current_projectID = projectID //当前项目ID 
        
        let params = {}
        params.tenant_id = userid
        params.parent_id = projectID

        let DataSource = []
        let that = this
        getsubtable(params).then((res)=>{        
          //[{childrens: [], id: 23, name: "震动盘子表2_0818", parentid: 1, serialno: "1"}]
          if(res.code == 500){//出现异常
            this.$message.warning('出现有异常');
            this.tabList = []
            //that.dataSource = []
            
            return 
          }
       
          let tabListSource = []      
          
          if(res.length == 0|| res == []){
            this.tabList = []    
            
            //如果此时子表为空 则把表格数据清空 把操作按钮影藏
            this.showDataList = []
            this.showOperator = false
        
            return 
          }
          res.forEach((item, index)=>{
            let tmp={}
            tmp.name = item.name
            tmp.key = item.id
            tmp.parentid = item.parentid
            tabListSource.push(tmp)
          })
          this.tabList = tabListSource

          this.activeKey =   this.tabList[0].key //默认是第一个子表 这时候 this.activeKey就是子表id

          this.current_subtableID = this.activeKey 
          this.tableActiveName =  this.tabList[0].name

          this.showOperator = true

          this.getTableDetail(this.activeKey)            
        })
      },
      getTableDetail(){
        let params = {}
        let subTableID = arguments[0]       
      
        this.current_subtableID = subTableID

        params.tenant_id = userid
        params.id = subTableID
        getdetailList(params).then((res)=>{
          let tem_data_array = []
          if(res.length!=0){
            res.forEach((item, index)=>{
              
              let tmp = {
                "tenant_id": item.tenant_id,
                "makeup": item.makeup,
                "ext10": item.ext10,
                "image_num":item.image_num,
                "name": item.extend_name,
                "remark": item.extend_remark,
                "img_name": item.img_name,
                "ext9": item.ext9,
                "ext8": item.ext8,
                "ext7": item.ext7,
                "ext6": item.ext6,
                "subtableId":item.id,//子表id也就是这个18            
                // "id": 18, 这个是子表id，我要是的material_id 也就是extendId
                "id":item.extendId,
                "ext5":item.ext5,
                "ext4": item.ext4,
                // "material_name": "111",
                "unit_id": 25,
                "ext3": item.ext3,
                "nums": item.nums,
                "ext2": item.ext2,
                "tech": item.tech,
                // "extendId": 700,
                // "extend_remark": "1",
                "unit": "件",
                "parent_id": item.parent_id,
                // "name": "子清单10",           
                "bar_code": item.bar_code         
              }
              tem_data_array.push(tmp)
            })

             this.dataList = tem_data_array
             this.showDataList = JSON.parse(JSON.stringify(this.dataList))
          }else{           
              this.dataList = []
              this.showDataList = []
          }         
        })        
      },
      tabchangecallback(){ //切换tab回调
        let args0 = arguments[0] //这个就是 子表id     

        this.tabList.forEach((item, index)=>{
          if(item.key == args0){
            this.tableActiveName = item.name
            return false
          }
        })

        this.getTableDetail(args0)
        this.current_subtableID = args0
      },
      //加载初始化列
      initColumnsSetting(){
        let columnsStr = Vue.ls.get('materialColumns')  //写入缓存的类 只有勾选了需要显示那些列的时候 才会触发 set('materialColumns')      
        if(columnsStr && columnsStr.indexOf(',')>-1) {
          this.settingColumns = columnsStr.split(',')
        }
      
        this.columns = this.defColumns.filter(item => {
          if (this.settingColumns.includes(item.dataIndex)) { //(this.settingColumns是有默认值的          
            return true
          }
          return false
        })  
      },
      //列设置更改事件
      onColChange (checkedValues) {
        this.columns = this.defColumns.filter(item => {
          if (checkedValues.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        let columnsStr = checkedValues.join()
     
        Vue.ls.set('materialColumns', columnsStr)
      },
      loadTreeData(){
        let that = this;
        let params = {};
        params.id='';
        queryMaterialCategoryTreeList(params).then((res)=>{
          //  console.log(" queryMaterialCategoryTreeList=")
          //  console.log(res) //这个返回的是跟目录 比如//目录1  0625构建盘
          if(res){
            that.categoryTree = [];
            for (let i = 0; i < res.length; i++) {
              let temp = res[i];
              that.categoryTree.push(temp);
            }
          }
        })
      },
      batchSetMaterialCurrentStock () {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
        } else {
          let ids = "";
          for (let a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ",";
          }
          let that = this;
          this.$confirm({
            title: "确认操作",
            content: "是否操作选中数据?",
            onOk: function () {
              that.loading = true;
              postAction(that.url.batchSetMaterialCurrentStockUrl, {ids: ids}).then((res) => {
                if(res.code === 200){
                  that.$message.info('修正库存成功！');
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.data.message);
                }
              }).finally(() => {
                that.loading = false;
              });
            }
          });
        }
      },
      batchEdit() {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
        } else {
          let ids = "";
          for (let a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ",";
          }
          this.$refs.batchSetInfoModalForm.edit(ids);
          this.$refs.batchSetInfoModalForm.title = "批量编辑";
        }
      },
      handleEdit: function (record) {
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.disableSubmit = false;
        if(this.btnEnableList.indexOf(1)===-1) {
          this.$refs.modalForm.isReadOnly = true
        }
      },
      searchReset() {
        this.queryParam = {
          mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        }
        this.loadData(1);
      },     
      addListOK(){
        this.getTableDetail(this.current_subtableID)
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>